public class LongestCommonSubsequence {
    // leetcode 最长公共子序列
    // https://leetcode.cn/problems/longest-common-subsequence/description/?envType=study-plan-v2&envId=top-100-liked
    public int longestCommonSubsequence1(String text1, String text2) {
        // dp[i][j]表示以字符串1 i位置为结尾的子序列和字符串2 j位置为结尾的子序列中最长公共子序列
        int len1 = text1.length(), len2 = text2.length();
        int[][] dp = new int[len1+1][len2+1];
        text1 = " " + text1;
        text2 = " " + text2;
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (text1.charAt(i) == text2.charAt(j)) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                }else {
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }
        return dp[len1][len2];
    }

    /**
     * 优化
     * @param text1
     * @param text2
     * @return
     */
    public int longestCommonSubsequence(String text1, String text2) {
        // dp[i][j]表示以字符串1 i位置为结尾的子序列和字符串2 j位置为结尾的子序列中最长公共子序列
        int len1 = text1.length(), len2 = text2.length();
        int[] dp = new int[len2+1];
        text1 = " " + text1;
        text2 = " " + text2;
        for (int i = 1; i <= len1; i++) {
            int prev = 0;
            for (int j = 1; j <= len2; j++) {
                int tmp = dp[j];
                if (text1.charAt(i) == text2.charAt(j)) {
                    dp[j] = prev + 1;
                }else {
                    dp[j] = Math.max(dp[j], dp[j-1]);
                }
                prev = tmp;
            }
        }
        return dp[len2];
    }
}
